package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel_website_db/models"
	"path/filepath"
	"strings"
)

type NovelController struct {
	beego.Controller
}

// 小说上传
func (c *NovelController) Add() {
	//接收数据
	title := c.GetString("title")
	content := c.GetString("content")
	//为空验证
	if title == "" || content == "" {
		res := Response{
			Code: 500,
			Msg:  "上传的数据不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//img
	file, header, err1 := c.GetFile("img")
	if err1 != nil {
		res := Response{
			Code: 500,
			Msg:  "请选择要上传的图片",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	defer file.Close() //延迟关闭

	//验证图片大小
	if header.Size > 3*1024*1024 {
		res := Response{
			Code: 500,
			Msg:  "图片过大,图片大小不超过3MB",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	//验证图片格式
	ext := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if ext[suffix] == false {
		res := Response{
			Code: 500,
			Msg:  "图片格式不正确,请选择png、jpg、jpeg格式的图片",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//保存路径
	path := "static/img/" + header.Filename
	//保存图片
	c.SaveToFile("img", path)

	//接收结构体
	var novel models.Novel
	//实例化数据
	novel.Title = title
	novel.Content = content
	novel.Img = "http://127.0.0.1:8080/" + path
	//调用方法，实现小说上传
	if novel.Add() != nil {
		res := Response{
			Code: 500,
			Msg:  "小说上传失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res := Response{
		Code: 200,
		Msg:  "上传成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}
